import { defineStore } from "pinia";
import { ref } from "vue";


export const useUserStore = (key) => defineStore(`cp-user-${key}`,()=>{
    //全局變量:登錄用戶
    //空對象的變量 通過 as 斷言指定類型
    const user = ref({})

    //方法
    //存儲
    const setUser = (userData)=>{
        user.value = userData
    }

    //刪除
    const delUser = () => {
        user.value = {}
    }

    //return { user, setUser, delUser }

    let remoteSetUser = null

    function updateFromSubApp() {
        if (remoteSetUser) {
          remoteSetUser(user.value)
        }
      }
    
      function setRemoteUpdater(fn) {
        remoteSetUser = fn
      }

    return { user, setUser, delUser, updateFromSubApp,setRemoteUpdater }
},
// 方式1：默認存儲所有數據，以store的ID作為存儲的key
// {
//     persist:true  //開啟數據持久化
// },
//方式2：自定義存儲的key，指定存儲那些數據
{
    persist: {
        key: `he-cp-user-${key}`,
        pick: ['user'],
        
    }
})()
